using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

using Volo.Abp.EntityFrameworkCore.Modeling;

using WL.Think.Abp.EntityFrameworkCore;

namespace Microsoft.EntityFrameworkCore;

public static class ModelBuilderExtension
{
    /// <summary>
    /// 配置实体映射
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="builder"></param>
    /// <param name="buildAction"></param>
    /// <returns></returns>
    public static ModelBuilder Mapping<TEntity>(this ModelBuilder builder, Action<EntityTypeBuilder<TEntity>>? buildAction = null, string? tableName = null, string? schema = null) where TEntity : class
    {
        builder.Entity<TEntity>(b =>
        {
            if(string.IsNullOrWhiteSpace(tableName))
            {
                var entityType = typeof(TEntity);
                var attribute = entityType.GetCustomAttribute<TableAttribute>();
                if(attribute != null)
                {
                    tableName = attribute.Name;
                    schema = attribute.Schema;
                }
                else
                {
                    tableName = entityType.Name;
                    if (ThinkDbContextTableOptions.RemoveSuffix != null && tableName.EndsWith(ThinkDbContextTableOptions.RemoveSuffix))
                    {
                        tableName = tableName.RemovePostFix(ThinkDbContextTableOptions.RemoveSuffix);
                    }
                }
            }
            tableName = ThinkDbContextTableOptions.DbTablePrefix + tableName;
            b.ToTable(tableName, schema ?? ThinkDbContextTableOptions.DbScheme);
            b.ConfigureByConvention();
            buildAction?.Invoke(b);
        });

        return builder;
    }
}
